﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.IO;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Navigation;

namespace BaiDuAPI
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        
        private string GeocodingAPIKey="f6a2d7d4f42480106f48369530c65bec";
      

        private void querryButton_Click(object sender, RoutedEventArgs e)
        {
            latTextBox.Text = "";
            lonTextBox.Text = "";

            string url = string.Format("http://api.map.baidu.com/geocoder?address={0}&output=xml&key={1}", addressTextBox.Text, GeocodingAPIKey);
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            MapUpdate forecastState = new MapUpdate();
            forecastState.AsyncRequest = wr;
            wr.BeginGetResponse(new AsyncCallback(HandleLocationResponse), forecastState);
            
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            addressTextBox.Text = "玉洁东街2号";
            latTextBox.Text="30.630892";
            lonTextBox.Text = " 104.071805";
        }


        
        public class MapUpdate
        {
            public HttpWebRequest AsyncRequest { get; set; }
            public HttpWebResponse AsyncResponse { get; set; }
        }

       
        
        
        public void HandleForecastResponse(IAsyncResult asyncResult)
        {
            // get the state information
            MapUpdate forecastState = (MapUpdate)asyncResult.AsyncState;
            HttpWebRequest wr = (HttpWebRequest)forecastState.AsyncRequest;

            // end the async request
            forecastState.AsyncResponse = (HttpWebResponse)wr.EndGetResponse(asyncResult);

            System.IO.Stream streamResult;
            double newLat = 0.00;
            double newLon = 0.00;
            string city, province, street, district;

            // create a temp collection for the new forecast information for each 
            // time period
            try
            {
                // get the stream containing the response from the async call
                streamResult = forecastState.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlMap = XElement.Load(streamResult);

                // find the source element and retrieve the city and elevation information
                XElement xmlCurrent = xmlMap.Descendants("location").First();
                newLat = (double)(xmlCurrent.Element("lat"));
                newLon = (double)(xmlCurrent.Element("lng"));              
                xmlCurrent = xmlMap.Descendants("result").First();
                    
                string address = (string)(xmlCurrent.Element("formatted_address"));
                xmlCurrent = xmlMap.Descendants("addressComponent").First();
                city = (string)(xmlCurrent.Element("city"));
                province = (string)(xmlCurrent.Element("province"));
                street = (string)(xmlCurrent.Element("street"));
                district = (string)(xmlCurrent.Element("district"));

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    latTextBox.Text = newLat.ToString();
                    lonTextBox.Text = newLon.ToString();
                    addressTextBox.Text = address;
                    cityTextBox.Text = city;
                });
            }
            catch (FormatException)
            {
                return;
            }

        }

        public void HandleLocationResponse(IAsyncResult asyncResult)
        {
            // get the state information
            MapUpdate forecastState = (MapUpdate)asyncResult.AsyncState;
            HttpWebRequest wr = (HttpWebRequest)forecastState.AsyncRequest;

            // end the async request
            forecastState.AsyncResponse = (HttpWebResponse)wr.EndGetResponse(asyncResult);

            System.IO.Stream streamResult;
            double newLat = 0.00;
            double newLon = 0.00;
            //string address = addressTextBox.Text;
            //string city = "";

            // MessageBox.Show("aa");
            // create a temp collection for the new forecast information for each 
            // time period
            try
            {
                // get the stream containing the response from the async call
                streamResult = forecastState.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlMap = XElement.Load(streamResult);

                // find the source element and retrieve the city and elevation information
                XElement xmlCurrent = xmlMap.Descendants("location").First();
                newLat = (double)(xmlCurrent.Element("lat"));
                newLon = (double)(xmlCurrent.Element("lng"));
                //xmlCurrent = xmlMap.Descendants("result").First();

               

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    latTextBox.Text = newLat.ToString();
                    lonTextBox.Text = newLon.ToString();

                });
            }
            catch (FormatException)
            {
                return;
            }

        }

        private void addressButton_Click(object sender, RoutedEventArgs e)
        {
            string url = string.Format("http://api.map.baidu.com/geocoder?location={0},{1}&output=xml&key={2}", latTextBox.Text, lonTextBox.Text, GeocodingAPIKey);
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            MapUpdate forecastState = new MapUpdate();
            forecastState.AsyncRequest = wr;
            wr.BeginGetResponse(new AsyncCallback(HandleForecastResponse), forecastState);
        }

        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/BaiDuAPI;component/Search.xaml?lat={0}&lon={1}",latTextBox.Text,lonTextBox.Text),UriKind.Relative));
        }
         
    }
}